<script>
import * as XLSX from "xlsx";

export default {
  data() {
    return {
      tableInfo: {
        data: [],
        cashUnite: '元',
        standUnite: 'kgce'
      },
      tableInfoColumns: [],
      subjectInfo: {
        label: '请选择用能主体',
        getLabel: function (arr) {
          if(!arr || arr.length < 1) {
            return '请选择用能主体'
          }
          let s = '';
          arr.forEach(function (i){
            if (s !== '') {
              s = s + ','
            }
            s = s + i.label
          })
          return s
        },
        dialogVisible: false,
        selected: [],
        treeData: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        }
      },
      dateRange: {
        dateType: '日',
        formatDateTye: function (){
          if (this.dateType === '时') {
            return 'hour'
          }
          if (this.dateType === '日') {
            return 'day'
          }
          if (this.dateType === '月') {
            return 'month'
          }
          if (this.dateType === '年') {
            return 'year'
          }
          return ''
        },
        selected: [new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 7), new Date()],
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        }
      }
    }
  },
  mounted() {
    this.fetchTreeData()
  },
  methods: {
    fetchData: function (){
      const formatSelectedTreeNode = function (arr) {
        const newArr = []
        arr.forEach(function (item) {
          const ojb = {}
          ojb.subjectType = item.type
          ojb.subjectId = item.id
          ojb.subjectName = item.label
          if (item.type === 'METER') {
            newArr.push(ojb)
          }
        })
        return newArr
      }
      const selectedList = formatSelectedTreeNode(this.subjectInfo.selected)
      if(selectedList.length < 1){
        this.$message('请选择用能主体')
        return
      }
      const data = {
        content:{
          subjects: selectedList,
          dateType: this.dateRange.formatDateTye(),
          fromDate: this.$getTimeInfo(this.dateRange.selected[0]).toMin,
          toDate: this.$getTimeInfo(this.dateRange.selected[1]).toMin,
        }
      }
      this.tableInfoColumns = []
      this.$axios({url:"/ems/client/energy/report/meter/energy/excel", data: data}).then((content) => {
        this.tableInfo = content
        if (this.tableInfo.list.length > 0 && this.tableInfo.list[0].dateInfos.length >0 && this.tableInfo.list[0].dateInfos[0].items.length > 0) {
          const tableInfoColumns = this.tableInfoColumns
          this.tableInfo.list[0].dateInfos[0].items.forEach(function (i) {
            tableInfoColumns.push({label: i.colDate})
          })
        }
      })
    },
    fetchTreeData: function () {
      const rebuildList = function (list) {
        list.forEach(function (item) {
          if (item.type !== 'METER') {
            item.disabled = true
          }
          if (item.children && item.children.length > 0) {
            rebuildList(item.children)
          }
        })
      }
      const data = {content: {excludeTypes:["POINT","GATEWAY","DIAGRAM"]}}
      this.$axios({url:'/ems/client/energy/search/subject/tree',data: data}).then((content) => {
        rebuildList(content.list)
        this.subjectInfo.treeData = content.list
      });
    },
    dialogConfirm: function () {
      this.subjectInfo.dialogVisible = false
      this.subjectInfo.selected = this.$refs.tree.getCheckedNodes()
      this.subjectInfo.label = this.subjectInfo.getLabel(this.subjectInfo.selected)
    },
    handleClose() {
      this.subjectInfo.dialogVisible = false
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    treeClick: function () {
      this.dialogVisible = false
    },
    exportExcel: function () {
      const tables = document.getElementById('data-table').getElementsByClassName('data_table_energy_device_excel');
      const wb = XLSX.utils.book_new();
      for (let i = 0; i < tables.length; i ++) {
        const table = tables[i]
        const ws = XLSX.utils.table_to_sheet(table)
        XLSX.utils.book_append_sheet(wb, ws, this.tableInfo.list[i].subjectName);
      }
      XLSX.writeFile(wb, '设备能耗统计报表_' + new Date().getTime()+ ".xlsx");
    }
  }
}
</script>

<template>
  <div>
    <el-row>
      <el-col :span="24">
        <el-button type="text" @click="subjectInfo.dialogVisible = true" style="background-color: white;width: 350px;color: rgb(192, 196, 204);">{{subjectInfo.label}}</el-button>
        <el-dialog
            title="提示"
            :visible.sync="subjectInfo.dialogVisible"
            width="30%"
            :before-close="handleClose">
          <el-tree
              class="filter-tree"
              show-checkbox
              :data="subjectInfo.treeData"
              :props="subjectInfo.defaultProps"
              :filter-node-method="filterNode"
              @node-click="treeClick"
              ref="tree">
          </el-tree>
          <span slot="footer" class="dialog-footer">
          <el-button @click="subjectInfo.dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogConfirm">确 定</el-button>
        </span>
        </el-dialog>
        &nbsp;
        <label>时间范围：&nbsp;</label>
        <el-radio-group v-model="dateRange.dateType">
          <el-radio-button label="日"></el-radio-button>
          <el-radio-button label="月"></el-radio-button>
          <el-radio-button label="年"></el-radio-button>
        </el-radio-group>
        &nbsp;
        <el-date-picker
            v-model="dateRange.selected"
            :type="dateRange.dateType==='时' ? 'datetimerange': (dateRange.dateType==='日' ? 'daterange':'monthrange')"
            :format="dateRange.dateType==='年' ? 'yyyy': ''"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="dateRange.pickerOptions">
        </el-date-picker>
        &nbsp;
        <el-button type="primary" @click="fetchData">查询</el-button>
        <el-button type="primary" plain @click="exportExcel" >导出</el-button>
      </el-col>
    </el-row>
    <el-row style="margin-top: 20px;">
      <el-col :span="24">
        <el-tabs type="border-card" id="data-table">
          <el-tab-pane v-for="(item, index) in tableInfo.list" :label="item.subjectName" :key="index">
            <el-table
                :data="item.dateInfos"
                stripe
                class="data_table_energy_device_excel"
                :ref="'data_table_energy_excel_' + index"
                style="width: 100%">
              <el-table-column prop="userDate" label="时间" align="center"></el-table-column>
              <el-table-column v-for="(item, index) in tableInfoColumns" :key="item" :label="item.label" align="center">
                <template scope="s">
                  {{$doubleLab(s.row.items[index].increaseStandValue)}} kgce
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </div>
</template>

<style>
#data-table table tr td {
  width: 120px;
  border: 1px solid rgb(235, 238, 245);
}
</style>
